package com.heima.behavlor.service.impl;
import java.util.Date;

import com.heima.behavlor.service.ApBehaviorEntryService;
import com.heima.behavlor.service.ApCollectionBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.CollectionBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.wemedia.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * @package com.heima.behavlor.service.impl
 * @Date 2022/3/8
 * @project heima-leadnews
 */
@Service
public class ApCollectionBehaviorServiceImpl implements ApCollectionBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 收藏行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collectBehavior(CollectionBehaviorDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApBehaviorEntry entry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), null);
        Query query = Query.query(Criteria.where("entryId").is(entry.getId()).and("articleId").is(dto.getArticleId()));
        if (dto.getOperation().equals(ApCollection.Type.ARTICLE.getCode())){
            ApCollection apcoll = mongoTemplate.findOne(query, ApCollection.class);
            if (apcoll==null){
                ApCollection apCollection = new ApCollection();
                apCollection.setEntryId(entry.getId());
                apCollection.setArticleId(dto.getArticleId());
                apCollection.setType(ApCollection.Type.ARTICLE.getCode());
                apCollection.setCollectionTime(new Date());
                mongoTemplate.save(apCollection);
            }else {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"请勿重复收藏");
            }
        }else {
            mongoTemplate.remove(query,ApCollection.class);
        }

        return ResponseResult.okResult();
    }
}
